package com.niit.commons.pool

import com.niit.commons.conf.ConfigurationManager
import com.niit.commons.constant.Constants
import org.apache.commons.pool2.impl.{GenericObjectPool, GenericObjectPoolConfig}

object CreateMySqlPool {
  // 加载JDBC驱动，只需要一次
  Class.forName("com.mysql.jdbc.Driver")
  private var genericObjectPool: GenericObjectPool[MySqlProxy] = null
  // 用于返回真正的对象池GenericObjectPool
  def apply(): GenericObjectPool[MySqlProxy] = {
    if (this.genericObjectPool == null) {
      this.synchronized {
        val jdbcUrl = ConfigurationManager.config.getString("jdbc.url")
        val jdbcUser = ConfigurationManager.config.getString(Constants.JDBC_USER)
        val jdbcPassword = ConfigurationManager.config.getString(Constants.JDBC_PASSWORD)
        val size = ConfigurationManager.config.getInt(Constants.JDBC_DATASOURCE_SIZE)

        val pooledFactory = new PooledMySqlClientFactory(jdbcUrl, jdbcUser, jdbcPassword)
        val poolConfig = {
          val c = new GenericObjectPoolConfig
          c.setMaxTotal(size)
          c.setMaxIdle(size)
          c
        }
        //返回一个对象池
        this.genericObjectPool = new GenericObjectPool[MySqlProxy](pooledFactory, poolConfig)
      }
    }
    genericObjectPool
  }
}
